package main

import (
	"flag"
	"fmt"
	"time"

	"searchcenter/internal/config"
	"searchcenter/internal/handler"
	"searchcenter/internal/svc"

	"github.com/hashicorp/consul/api"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/service"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/zero-contrib/zrpc/registry/consul"
)

var configFile = flag.String("f", "etc/searchcenter-api.yaml", "the config file")

func main() {
	flag.Parse()

	// 1. 加载本地基础配置
	var baseConfig config.BaseConfig
	conf.MustLoad(*configFile, &baseConfig)
	config.SetBaseConfig(baseConfig) // 设置到全局变量中

	// 2. 从Consul KV加载配置
	kvConfig, err := loadConfigFromConsulKV(
		baseConfig.Consul.Host,
		baseConfig.Consul.ConfigKey,
		baseConfig.Consul.Token,
	)
	if err != nil {
		panic(fmt.Errorf("failed to load config from consul kv: %v", err))
	}

	// 3. 解析合并配置
	var c config.Config
	if err := conf.LoadFromJsonBytes(kvConfig, &c); err != nil {
		panic(fmt.Errorf("failed to parse consul kv config: %v", err))
	}

	// 4. 注册服务到Consul
	listenOn := fmt.Sprintf("%s:%d", c.Host, c.Port)
	err = consul.RegisterService(listenOn, consul.Conf{
		Host:  baseConfig.Consul.Host,
		Key:   baseConfig.Consul.Key,
		Token: baseConfig.Consul.Token,
		TTL:   baseConfig.Consul.TTL,
	})
	if err != nil {
		panic(err)
	}

	// 5. 创建服务上下文
	ctx := svc.NewServiceContext(c)

	// 6. 创建服务组
	serviceGroup := service.NewServiceGroup()
	defer serviceGroup.Stop()

	// 7. 添加HTTP服务（总是启动，不检查模式）
	server := rest.MustNewServer(c.RestConf)
	defer server.Stop()
	handler.RegisterHandlers(server, ctx)
	serviceGroup.Add(server)

	// 9. 打印服务初始化状态
	printServiceStatus(ctx, listenOn)

	fmt.Printf("Starting server at %s...\n", listenOn)
	serviceGroup.Start()
}

func printServiceStatus(ctx *svc.ServiceContext, listenOn string) {
	fmt.Println("\n=== 服务初始化状态 ===")
	fmt.Printf("服务地址: %s\n", listenOn)
	fmt.Println("====================")
}

func loadConfigFromConsulKV(consulHost, consulKey, consulToken string) ([]byte, error) {
	config := api.DefaultConfig()
	config.Address = consulHost
	config.Token = consulToken
	config.WaitTime = 5 * time.Second

	client, err := api.NewClient(config)
	if err != nil {
		return nil, fmt.Errorf("failed to create consul client: %v", err)
	}

	kv := client.KV()
	pair, _, err := kv.Get(consulKey, nil)
	if err != nil {
		return nil, fmt.Errorf("failed to get kv from consul: %v", err)
	}

	if pair == nil {
		return nil, fmt.Errorf("no such key in consul: %s", consulKey)
	}

	return pair.Value, nil
}
